<template>
  <j-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    switchFullscreen
    @ok="handleSubmit"
    @cancel="close"
    style="top:50px"
    cancelText="关闭"
  >
    <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px">
      <a-col :md="6" :sm="24" class="visible-lg-block">
        <a-card :bordered="false">
          <!--组织机构-->
          <a-directory-tree
            selectable
            :selectedKeys="selectedDepIds"
            :checkStrictly="true"
            :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
            :treeData="departTree"
            :expandAction="false"
            :expandedKeys.sync="expandedKeys"
            @select="onDepSelect"
          />
        </a-card>
      </a-col>
      <a-col :md="18" :sm="24">
        <a-card :bordered="false">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24" >
              用户账号:
                <a-input-search
                  :style="{width:'150px',marginBottom:'15px'}"
                  placeholder="请输入账号"
                  v-model="queryParam.username"
                  @search="onSearch"
                ></a-input-search>
            </a-col>
            <a-col :md="8" :sm="24" >
              用户姓名:
                <a-input-search
                  :style="{width:'150px',marginBottom:'15px'}"
                  placeholder="请输入姓名"
                  v-model="queryParam.realname"
                  @search="onSearch"
                ></a-input-search>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-button @click="searchReset(1)" style="margin-left: 20px" icon="redo">重置</a-button>
            </a-col>
          </a-row>
          <!--用户列表-->
          <a-table
            ref="table"
            :scroll="scrollTrigger"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: getType}"
            :loading="loading"
            @change="handleTableChange">
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </j-modal>
</template>

<script>
import { filterObj, pushIfNotExist } from '@/utils/util'
import { queryDepartTreeList, getUserList, queryUserByDepId } from '@/api/api'

export default {
  name: 'JSelectUserByDepModal',
  components: {},
  props: ['modalWidth', 'multi', 'userIds'],
  data() {
    return {
      queryParam: {
        username: ''
      },
      columns: [
        {
          title: '用户账号',
          align: 'center',
          dataIndex: 'username'
        },
        {
          title: '用户姓名',
          align: 'center',
          dataIndex: 'realname'
        },
        {
          title: '性别',
          align: 'center',
          dataIndex: 'sex',
          customRender: function(text) {
            if (text === 1) {
              return '男'
            } else if (text === 2) {
              return '女'
            } else {
              return text
            }
          }
        },
        {
          title: '手机',
          align: 'center',
          dataIndex: 'phone'
        },
        {
          title: '部门',
          align: 'center',
          dataIndex: 'orgCode'
        }
      ],
      scrollTrigger: {},
      dataSource: [],
      selectedRowKeys: [],
      selectUserRows: [],
      selectUserIds: [],
      selectionRows: [],
      title: '根据部门选择用户',
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      selectedDepIds: [],
      departTree: [],
      visible: false,
      form: this.$form.createForm(this),
      loading: false,
      expandedKeys: []
    }
  },
  computed: {
    // 计算属性的 getter
    getType: function() {
      return this.multi == true ? 'checkbox' : 'radio'
    }
  },
  watch: {
    userIds: {
      immediate: true,
      handler() {
        this.initUserNames()
      }
    }
  },
  created() {
    // 该方法触发屏幕自适应
    this.resetScreenSize()
    this.loadData()
  },
  methods: {
    initUserNames() {
      if (this.userIds) {
        // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询，防止后台进行了模糊匹配，导致查询结果不准确
        const values = this.userIds.split(',') + ','
        getUserList({
          username: values,
          pageNo: 1,
          pageSize: values.length
        }).then((res) => {
          if (res.success) {
            const selectedRowKeys = []
            const realNames = []
            this.selectionRows = []
            res.result.records.forEach(user => {
              realNames.push(user['realname'])
              selectedRowKeys.push(user['id'])
              this.selectionRows.push(user)
            })
            this.selectedRowKeys = selectedRowKeys
            this.$emit('initComp', realNames.join(','))
          }
        })
      } else {
        // JSelectUserByDep组件bug issues/I16634
        this.$emit('initComp', '')
      }
    },
    async loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      if (this.selectedDepIds && this.selectedDepIds.length > 0) {
        await this.initQueryUserByDepId(this.selectedDepIds)
      } else {
        this.loading = true
        const params = this.getQueryParams()// 查询条件
        await getUserList(params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total
          }
        }).finally(() => {
          this.loading = false
        })
      }
    },
    // 触发屏幕自适应
    resetScreenSize() {
      const screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.scrollTrigger = { x: 800 }
      } else {
        this.scrollTrigger = {}
      }
    },
    showModal() {
      this.visible = true
      this.queryDepartTree()
      this.initUserNames()
      this.loadData()
      this.form.resetFields()
    },
    getQueryParams() {
      const queryParam = {}
      for (const key in this.queryParam) {
        queryParam[key] = this.queryParam[key] + '*'
      }
      const param = Object.assign({}, queryParam, this.isorter)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField() {
      let str = 'id,'
      for (let a = 0; a < this.columns.length; a++) {
        str += ',' + this.columns[a].dataIndex
      }
      return str
    },
    searchReset(num) {
      const that = this
      if (num !== 0) {
        that.queryParam = {}
        that.loadData(1)
      }
      that.selectedRowKeys = []
      that.selectUserIds = []
      that.selectedDepIds = []
    },
    close() {
      this.searchReset(0)
      this.visible = false
    },
    handleTableChange(pagination, filters, sorter) {
      // TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order === 'ascend' ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleSubmit() {
      const that = this
      this.getSelectUserRows()
      that.$emit('ok', that.selectUserRows, that.selectUserIds)
      that.searchReset(0)
      that.close()
    },
    // 获取选择用户信息
    getSelectUserRows(rowId) {
      // const dataSource = this.dataSource
      let userIds = ''
      this.selectUserRows = []
      for (const row of this.selectionRows) {
        if (this.selectedRowKeys.includes(row.id)) {
          this.selectUserRows.push(row)
          userIds = userIds + ',' + row.username
        }
      }
      this.selectUserIds = userIds.substring(1)
    },
    // getSelectUserRows() {
    //     this.selectUserRows = []
    //     for (let row of this.selectionRows) {
    //       if (this.selectedRowKeys.includes(row.id)) {
    //         this.selectUserRows.push(row)
    //       }
    //     }
    //     this.selectUserIds = this.selectUserRows.map(row => row.username).join(',')
    //   },
    // 点击树节点,筛选出对应的用户
    onDepSelect(selectedDepIds) {
      if (selectedDepIds[0] != null) {
        this.initQueryUserByDepId(selectedDepIds) // 调用方法根据选选择的id查询用户信息
        if (this.selectedDepIds[0] !== selectedDepIds[0]) {
          this.selectedDepIds = [selectedDepIds[0]]
        }
      }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      console.log(this.selectionRows)
      // this.selectionRows = selectionRows
      selectionRows.forEach(row => pushIfNotExist(this.selectionRows, row, 'id'))
    },
    onSearch() {
      this.loadData(1)
    },
    // 根据选择的id来查询用户信息
    initQueryUserByDepId(selectedDepIds) {
      this.loading = true
      return queryUserByDepId({ id: selectedDepIds.toString() }).then((res) => {
        if (res.success) {
          this.dataSource = res.result
          this.ipagination.total = res.result.length
        }
      }).finally(() => {
        this.loading = false
      })
    },
    queryDepartTree() {
      queryDepartTreeList().then((res) => {
        if (res.success) {
          this.departTree = res.result
          // 默认展开父节点
          this.expandedKeys = this.departTree.map(item => item.id)
        }
      })
    },
    modalFormOk() {
      this.loadData()
    }
  }
}
</script>

<style scoped>
  .ant-table-tbody .ant-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  #components-layout-demo-custom-trigger .trigger {
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color .3s;
  }
</style>
